package com.cx.service.impl;

import com.cx.mapper.CityMapper;
import com.cx.mapper.CountryMapper;
import com.cx.pojo.City;
import com.cx.pojo.Country;
import com.cx.service.CityService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class CityServiceImpl implements CityService {

    @Autowired
    private CityMapper mapper;

    @Autowired
    private CountryMapper countryMapper;

    @Override
    public List<City> findAll() {
        List<City> cities = mapper.selectByExample(null);
        return cities;
    }

    @Override
    public PageInfo<City> findPages(Integer pageNumber, Integer number) {
        PageHelper.startPage(pageNumber,number);
        List<City> cities = mapper.selectByExample(null);
        for (City city:cities){
            Country country = countryMapper.selectByPrimaryKey(city.getCityid());
            System.out.println(country);
            city.setCountry(country);
        }
        return new PageInfo<>(cities);
    }

    @Override
    public PageInfo<City> delete(Integer cityid) {
        mapper.deleteByPrimaryKey(cityid);
        List<City> cities = mapper.selectByExample(null);
        for (City city:cities){
            Country country = countryMapper.selectByPrimaryKey(city.getCityid());
            city.setCountry(country);
        }
        return new PageInfo<>(cities);
    }

    @Override
    public City findById(Integer cityid) {
        return mapper.selectByPrimaryKey(cityid);
    }

    @Override
    public int update(City city) {
        return mapper.updateByPrimaryKeySelective(city);
    }

    @Override
    public Map<String,Object> findByIdAndCountry(Integer cityid) {
        Map<String,Object> map = new HashMap<>();
        map.put("city",mapper.selectByPrimaryKey(cityid));
        map.put("country",countryMapper.selectByExample(null));
        return map;
    }

    @Override
    public int delets(Integer cityid) {
        return mapper.deleteByPrimaryKey(cityid);
    }

    @Override
    public int add(City city) {
        return mapper.insert(city);
    }
}
